package es

import (
	"context"
	"easyblog/utils/log"
	beego "github.com/beego/beego/v2/server/web"
	"github.com/olivere/elastic/v7"
	"time"
)

var (
	EsClient *elastic.Client

	esEnable,_ = beego.AppConfig.Bool("esenable")
	esHost,_   = beego.AppConfig.String("eshost")
	esPort,_   = beego.AppConfig.String("esport")
	esIndex,_  = beego.AppConfig.String("esindex")
)

type esArticle struct {
	ID		 int
	Title    string
	Desc     string
	Content  string
	CreateTime time.Time
}

const mapping = `
{
	"mappings": {
		"properties": {
			"Title": {
				"type": "text",
				"analyzer": "ik_max_word",
				"search_analyzer": "ik_smart"
			},
			"Desc": {
				"type": "text",
				"analyzer": "ik_max_word",
				"search_analyzer": "ik_smart"
			},
			"Content": {
				"type": "text",
				"analyzer": "ik_max_word",
				"search_analyzer": "ik_smart"
			}
		}
	}
}`

func init()  {
	if !esEnable {
		return
	}

	url := "http://"+esHost+":"+esPort
	client, err := elastic.NewClient(elastic.SetURL(url))
	if err != nil {
		log.Logger.Error("es create new client err ", err.Error())
	}
	EsClient = client

	createIndex()
}

func createIndex(){
	ctx := context.Background()
	exists, err := EsClient.IndexExists(esIndex).Do(ctx)
	if err != nil {
		log.Logger.Error(" check index exists err",err.Error())
	}
	if !exists {
		_,err := EsClient.CreateIndex(esIndex).Body(mapping).Do(ctx)
		if err != nil {
			log.Logger.Error("create index err ",err.Error())
		}
	}
}
